import React, { useState, useEffect } from 'react';
import { Button, Dropdown, Space } from 'antd';

import '../../style/main.css';
import '../../style/kuangjia.css';

const DayRecommend = ({ onSongSelect }) => {
  const handleSongClick = async (song) => {
    onSongSelect(song)
  }
  const [songLists, setSongLists] = useState([]);
  useEffect(() => {
    fetch('http://localhost:3000/recommend/songs')
      .then((response) => response.json())
      .then((data) => {
        setSongLists(data.data.dailySongs);
      })
      .catch((error) => console.error('Error fetching recommendsongs data:', error));
  }, []);

  const formatDuration = (duration) => {
    const minutes = Math.floor(duration / 60000);
    const seconds = ((duration % 60000) / 1000).toFixed(0);
    return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
  };

  const items = (songId) => [
    {
      key: '1',
      label: (
        <a
          href="#"
          onClick={(e) => {
            e.preventDefault(); // 阻止默认行为
            const song = songData.find((s) => s.id === songId); // 获取当前歌曲
            if (song.liked) {
              alert("歌曲已收藏");
            } else {
              handleLikeClick(song.id); // 执行收藏/取消收藏操作
            }
          }}
        >
          收藏
        </a>
      ),
    },
    {
      key: '2',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.aliyun.com">
          下载
        </a>
      ),
    },
    {
      key: '3',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
          添加到歌单
        </a>
      ),
    },
    {
      key: '4',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
          添加到播放
        </a>
      ),
    },
  ];

  const getPlayUrl = (id) => {
    return fetch(`http://localhost:3000/song/url?id=${id}`)
      .then((response) => response.json())
      .then((data) => data.data[0]?.url || '')
      .catch((error) => {
        console.error('Error fetching song URL:', error);
        return '';
      });
  };

  const checkFavorStatus = async (songId) => {
    try {
      const response = await fetch(`http://localhost:8088/favor/${songId}`);
      const data = await response.json();
      if (data.code === 200 && data.data !== null) {
        return true;
      } else {
        return false;
      }
    } catch (error) {
      console.error("Error checking favor status: ", error);
      return false; // 默认未收藏
    }
  };

  const [songData, setSongData] = useState([])
  useEffect(() => {
    if (songLists.length > 0) {
      const fetchSongData = async () => {
        const data = await Promise.all(
          songLists.map(async (song) => {
            const playUrl = await getPlayUrl(song.id);
            const isFavorited = await checkFavorStatus(song.id);
            return {
              id: song.id,
              name: song.name,
              singer: song.ar[0]?.name || '未知',
              albumPic: song.al.picUrl,
              albumName: song.al.name,
              duration: song.dt,
              playUrl,
              liked: isFavorited,
            }
          })
        );
        setSongData(data);
      };
      fetchSongData();
    }
  }, [songLists]);

  const handleLikeClick = async (songId) => {
    const song = songData.find((s) => s.id === songId);
    const newLikedStatus = !song.liked;
    // 更新状态
    setSongData((prevSongs) =>
      prevSongs.map((s) =>
        s.id === songId ? { ...s, liked: newLikedStatus } : s
      )
    );
    const songPost = {
      musicId: song.id,
      musicName: song.name,
      artId: song.singer,
      album: song.albumName,
      coverUrl: song.albumPic,
      playUrl: song.playUrl,
    };
    try {
      if (newLikedStatus) {
        // 收藏操作 (POST 请求)
        const response = await fetch("http://localhost:8088/favor", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(songPost),
        });

        if (!response.ok) {
          throw new Error("Failed to update favor status");
        }

        console.log("Successfully added song to favorites:", songId);
      } else {
        // 取消收藏操作 (DELETE 请求)
        const response = await fetch(`http://localhost:8088/favor/${songId}`, {
          method: "DELETE",
        });

        if (!response.ok) {
          throw new Error("Failed to remove song from favorites");
        }

        console.log("Successfully removed song from favorites:", songId);
      }
    } catch (error) {
      console.error("Error handling favor request: ", error);
    }
  };

  return (
    <div className="page">
      <div className="playlistcontainer">
        <div className="playlistinformation">
          <div className="playlistImg">
            <img src="src/img/Dayimg.svg" alt="" />
          </div>
          <div className="list-maininformation">
            <div id="playlistname">每日推荐</div>
            <div className="playlistavatar">
              <img src="src/img/dayAvatar.png" alt="" />
              <span id="playlistusernickname">云官方歌单</span>
            </div>
            <div className="introduce">根据你的口味生成，每日6:00更新</div>
            <div className="playlistControl">
              <button><i className="ri-play-fill"></i> 播放</button>
              <button><i className="ri-download-fill"></i> 下载</button>
              <button><i className="ri-heart-3-line"></i> 收藏</button>
              <button><i className="ri-share-fill"></i> 分享</button>
            </div>
          </div>
        </div>
        <div className="playlistnav">
          <ul>
            <li>歌曲</li>
            <li>评论</li>
          </ul>
        </div>
      </div>
      <div className="search_songlist">
        <div className="serch_nav">
          <div>歌名/歌手</div>
          <div className="serch_nav_right">
            <div>专辑</div>
            <div>时长</div>
          </div>
        </div>
        <ul>
          {songData.map((item, index) => (
            <li key={index} onDoubleClick={() => handleSongClick(item)}>
              <div className="hideicon">
                <i className="ri-play-fill"></i>
              </div>
              <div className="search_songlist_left">
                <div className="song_information">
                  <img
                    src={item.albumPic}
                    alt={item.name}
                  />
                  <div className="song_name">
                    <span id="songname">{item.name}</span>
                    <span id="singer">{item.singer}</span>
                  </div>
                </div>
                <div className="dowhat">
                  <i
                    className={item.liked ? "ri-heart-3-fill" : "ri-heart-3-line"}// 根据每首歌的状态切换图标
                    onClick={(e) => {
                      e.stopPropagation();
                      handleLikeClick(item.id);
                    }}
                  ></i>
                  <div className='menu'>
                    <Space direction="vertical">
                      <Space wrap>
                        <Dropdown
                          menu={{
                            items: items(item.id), // 动态传入当前歌曲的 ID
                          }}
                          placement="topLeft"
                          trigger={['click']}
                        >
                          <i className="ri-menu-4-line"></i>
                        </Dropdown>
                      </Space>
                    </Space>
                  </div>
                </div>
              </div>
              <div className="search_songlist_right">
                <div id="songalbum">{item.albumName}</div>
                <div id="songduration">{item.duration ? formatDuration(item.duration) : '00:00'}</div>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};

export default DayRecommend;
